# -*- coding:utf-8 -*-
"""
该脚本用来检测maya中的一些内容
"""
import os
import time
from .Camera import get_main_camera,get_camera_BGimg
# from .RenameDetection import rename_detect
try:
    import maya.cmds as cmds
    import maya.mel as mel
    import maya.app.renderSetup.model.renderSetup as renderSetup
    import pymel.core as pm
except Exception as test_ERR:
    print('test')


def optimizeScene():
    """
    优化场景
    :return:
    """
    start = time.time()
    try:
        os.environ["MAYA_TESTING_CLEANUP"] = "1"
        pm.mel.cleanUpScene(1)
        del os.environ["MAYA_TESTING_CLEANUP"]
        result_info = {'result': 'OK', 'info': ''}
    except Exception as optimizeScene_ERR:
        result_info = {'result': 'ERROR', 'info': str(optimizeScene_ERR)}

    end = time.time()
    print(u'优化场景时间:',end-start)

    return result_info

def checkCamera():
    """
    检测相机,是否存在相机
    模型提交不难带相机
    """
    cameras = cmds.ls(type='camera')
    if cameras:
        result_info = {'result': 'OK', 'info': u'没有相机'}
    else:
        result_info = {'result': 'ERROR', 'info': []}
    return result_info

    return result

def checkMainCamera(asset_shot_name):
    """
    检测主相机
    :param asset_shot_name: 资产或镜头名称
    :return:
    """

    main_camera = get_main_camera(asset_shot_name)
    if main_camera:
        result_info = {'result': 'OK', 'info': u'存在主相机'}
    else:
        result_info = {'result': 'ERROR', 'info': u'不存在主相机'}
    return result_info


def checkOverFourFace():
    """
    检测超过四边的面的模型,并显示
    :return:
    """
    start = time.time()
    result = pm.ls(type='mesh')
    overs = []
    for i in result:
        i.setAttr('displayNonPlanar',1)
        i.setAttr('displayColors',1)
        faces = i.faces
        for f in faces:
            f_name = f.name()
            edges = f.getEdges()
            edge_numbers = len(edges)
            if edge_numbers >= 5:
                pm.polyColorPerVertex(f,rgb=(1,0,0))
                if f_name not in overs:
                    overs.append(f_name)
    if overs:
        result_info = {'result':'ERROR','info':overs}
    else:  #
        result_info = {'result': 'OK', 'info': []}
    end = time.time()
    print(u'超四边面检测:',end-start)
    return result_info

def checkCameraBGImg(camera_name):
    """
    检测相机背景图
    :param main_camera: 主相机名称
    :return:
    """
    BG_path = ''
    main_camera = get_main_camera(camera_name)
    result = ''
    if main_camera:
        result = cmds.listConnections(cmds.listRelatives(camera_name),type='imagePlane')
    #print(result)     #[u'CXRX_pianhua_001Shape1->imagePlane1']
    if result:
        shapes = cmds.listRelatives(result)
        BG_path = cmds.getAttr(shapes[0]+'.imageName')

    if BG_path:
        if ':' in BG_path and BG_path[0] in ['C','D','E','F']:  # 是本地路径
            result_info = {'result':'ERROR','info':'Local Path'}
        else:  # 不是本地路径
            result_info = {'result': 'OK', 'info': ''}
    else:  # 没有背景图
        result_info = {'result': 'OK', 'info': 'No BG Image'}

    return result_info


def checkLockCamera(camera_name):
    """
    检测相机属性是否锁定
    :param main_camera: 主相机transform
    :return:
    """
    main_camera = get_main_camera(camera_name)
    if main_camera:
        errors = []
        attr_list = ['tx','ty','tz','rx','ry','rz','sx','sy','sz']
        for i in attr_list:
            result = cmds.getAttr('{}.{}'.format(camera_name,i), lock=True)
            if not result:
                errors.append(i)
        if errors:
            result_info = {'result': 'ERROR', 'info': errors}
        else:
            result_info = {'result': 'OK', 'info': []}
    else:
        result_info = {'result': 'ERROR', 'info': [u'没有主相机']}

    return result_info

def lockCamera():
    result = False
    sn = cmds.ls(sl=1)
    if not sn:
        choose = cmds.confirmDialog(title='tip', message=u'请先选择相机', icon='warning',
                                    button=['OK'], defaultButton=u'OK', cancelButton=u'OK',
                                    dismissString=u'OK')
    else:
        shape = cmds.listRelatives(sn[0])[0]
        if cmds.nodeType(shape) == 'camera':
            attr_list = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz']
            for i in attr_list:
                cmds.setAttr('{}.{}'.format(sn[0], i), lock=True)
            result = True
        else:
            choose = cmds.confirmDialog(title='tip', message=u'请先选择相机', icon='warning',
                                        button=['OK'], defaultButton=u'OK', cancelButton=u'OK',
                                        dismissString=u'OK')
    return result


def checkDSO():
    """
    检测arnold代理路径是否在网盘上
    :return:
    """
    err_dso = []
    ars = cmds.ls(type='aiStandIn')

    if ars:
        for i in ars:
            dso = cmds.getAttr('{}.dso'.format(i))
            if ':' in dso and dso[0] in ['C','D','E','F']:  # 是本地路径
                err_dso.append(i)

    # else:
    #     result_info = {'result': 'OK', 'info': 'No DSO'}

    if err_dso:
        result_info = {'result': 'ERROR', 'info': err_dso}
    else:
        result_info = {'result':'OK','info':[]}

    return result_info




def checkName():
    """
    重命名检测
    :return:
    """
    transforms = cmds.ls(type='transform', l=1)
    mesh_names = []
    repeat_meshs = []
    for s in transforms:
        name = s.split('|')
        mesh_name = name[-1]
        if mesh_name not in mesh_names:
            mesh_names.append(mesh_name)
        else:
            repeat_meshs.append(s)
    print('repeat_meshs:', repeat_meshs)
    if repeat_meshs:
        result_info = {'result':'ERROR','info':repeat_meshs}
    else:
        result_info = {'result':'OK','info':[]}

    return result_info

def auto_rename():

    meshs = cmds.ls(type='mesh', l=1)
    mesh_names = []

    count = 0
    for s in meshs:
        name = s.split('|')
        ns = name[:-1]
        mesh_name = name[-2]
        long_mesh_name = '|'.join(ns)
        if mesh_name not in mesh_names:
            mesh_names.append(mesh_name)
        else:
            new_mesh_name = mesh_name + '_' + str(count)
            if new_mesh_name in mesh_names:
                new_mesh_name += '_'
            cmds.rename(long_mesh_name, new_mesh_name)
            mesh_names.append(new_mesh_name)
            count += 1

    return True

def checkDisplayLayers():
    """
    检测显示层
    :return:
    """
    layers = []
    displayLayers = cmds.ls(type="displayLayer")
    for i in displayLayers:
        if 'defaultLayer' not in i:
            layers.append(i)
    if layers:
        result_info = {'result': 'ERROR', 'info': layers}
    else:
        result_info = {'result': 'OK', 'info': []}

    return result_info

def checkRenderLayers():
    """
    检测渲染层
    :return:
    """
    layers = []
    renderLayers = cmds.ls(type="renderLayer")
    for i in renderLayers:
        if 'defaultRenderLayer' not in i:
            layers.append(i)
    if layers:
        result_info = {'result': 'ERROR', 'info': layers}
    else:
        result_info = {'result': 'OK', 'info': []}

    return result_info

def clearDisplayLayers():
    """
    清除所有显示层
    :return:
    """
    for layer in cmds.ls(type="displayLayer"):
        if 'defaultLayer' not in layer:
            cmds.delete(layer)

def clearRenderLayers():
    """
    清除所有渲染层
    :return:
    """
    # for layer in cmds.ls(type="renderLayer"):
    #     if layer != 'defaultRenderLayer':
    #         cmds.delete(layer)

    rs = renderSetup.instance()
    rs.clearAll()

def clearLayers():
    """
    清除所有显示层与渲染层
    :return:
    """
    clearDisplayLayers()
    clearRenderLayers()

def checkPrimMaterial():
    """
    检测是否有按面上材质
    :return:
    """
    start = time.time()
    default_mat = [u'initialParticleSE', u'initialShadingGroup']
    ses = cmds.ls(type='shadingEngine')
    has_face = []
    for se in ses:
        if se not in default_mat:
            con = cmds.sets(se, q=True)
            for c in con:
                if c.count('f[') > 0 and se not in has_face:
                    has_face.append(se)
    if has_face:
        result_info = {'result': 'ERROR', 'info': has_face}
    else:
        result_info = {'result': 'OK', 'info': []}
    end = time.time()
    print(u'面上材质检测:',end-start)
    return result_info

def checkMaterialTexture():
    """
    检测材质
    :return:
    """
    files = cmds.ls(type='file')
    errs = []
    if files:
        for f in files:
            img_path = cmds.getAttr(f + '.fileTextureName')
            if ':' in img_path and img_path[0] in ['C','D','E','F']:  # 是本地路径
                errs.append(img_path)

    if errs:
        result_info = {'result': 'ERROR', 'info': errs}
    else:
        result_info = {'result': 'OK', 'info': []}

    return result_info

def checkColorSpace():
    """
    检测图片色彩空间
    :return:
    """
    files = cmds.ls(type='file')
    # errs = []
    cs_map = {}
    if files:
        for f in files:
            cs = cmds.getAttr(f + '.colorSpace')
            if cs not in cs_map.keys():
                cs_map[cs] = [f]
            else:
                cs_map[cs].append(f)


    if len(cs_map.keys())>1 :
        result_info = {'result': 'ERROR', 'info': cs_map}
    else:
        result_info = {'result': 'OK', 'info': {}}

    return result_info


def checkUV():
    """
    检查UVset是否只有一层
    :return:
    """
    sn = cmds.ls(l=1,type='mesh')

    wrong_uv_set=[]
    for m in sn:
        all_uv_set = cmds.polyUVSet(m, query=True, allUVSets=True)
        # print(m,all_uv_set)
        if len(all_uv_set)>1:
            wrong_uv_set.append(m)
    if wrong_uv_set:
        result_info = {'result': 'ERROR', 'info': wrong_uv_set}
    else:
        result_info = {'result': 'OK', 'info': []}

    return result_info


def checkRigGrp():
    """
    检查绑定大组名称是否正确
    :return:
    """
    result = False
    result = cmds.ls(type='transform')
    for g in result:
        if g.endswith('rig_Grp'):
            # print(g)
            children = cmds.listRelatives(g, fullPath=1)
            # print(children)
            for c in children:
                if c.endswith('Group'):
                    r_children = cmds.listRelatives(c, fullPath=1)
                    # print('r_children:', r_children)
                    for r in r_children:
                        if r.endswith('Rig_all') or r.endswith('rig_all'):
                            # print(r)
                            main_children = cmds.listRelatives(r, fullPath=1)
                            for m in main_children:
                                if m.endswith('Main'):
                                    result = True
    if result:
        result_info = {'result': 'OK', 'info': ''}
    else:
        result_info = {'result': 'ERROR', 'info': u'不存在rig_Grp'}

    return result_info

def checkHumanRig():
    """
    检查人物骨骼名称
    :return:
    """
    # result = True
    human_joints = [u'HeadEnd_M', u'EyeEnd_R', u'Eye_R', u'JawEnd_M', u'Jaw_M',
                   u'EyeEnd_L', u'Eye_L', u'Head_M', u'Neck_M', u'MiddleFinger4_R',
                   u'MiddleFinger3_R', u'MiddleFinger2_R', u'MiddleFinger1_R', u'ThumbFinger4_R', u'ThumbFinger3_R',
                   u'ThumbFinger2_R', u'ThumbFinger1_R', u'IndexFinger4_R', u'IndexFinger3_R', u'IndexFinger2_R',
                   u'IndexFinger1_R', u'PinkyFinger4_R', u'PinkyFinger3_R', u'PinkyFinger2_R', u'PinkyFinger1_R',
                   u'RingFinger4_R', u'RingFinger3_R', u'RingFinger2_R', u'RingFinger1_R', u'Cup_R',
                   u'Wrist_R', u'ElbowPart1_R', u'Elbow_R', u'Shoulder_R', u'Scapula_R',
                   u'MiddleFinger4_L', u'MiddleFinger3_L', u'MiddleFinger2_L', u'MiddleFinger1_L', u'ThumbFinger4_L',
                   u'ThumbFinger3_L', u'ThumbFinger2_L', u'ThumbFinger1_L', u'IndexFinger4_L', u'IndexFinger3_L',
                   u'IndexFinger2_L', u'IndexFinger1_L', u'PinkyFinger4_L', u'PinkyFinger3_L', u'PinkyFinger2_L',
                   u'PinkyFinger1_L', u'RingFinger4_L', u'RingFinger3_L', u'RingFinger2_L', u'RingFinger1_L',
                   u'Cup_L', u'Wrist_L', u'ElbowPart1_L', u'Elbow_L', u'Shoulder_L',
                   u'Scapula_L', u'Chest_M', u'Spine1_M', u'ToesEnd_R', u'Toes_R',
                   u'Ankle_R', u'Knee_R', u'Hip_R', u'ToesEnd_L', u'Toes_L',
                   u'Ankle_L', u'Knee_L', u'Hip_L', u'Root_M']

    errors = []
    joints = cmds.ls(type='joint')
    for i in human_joints:
        if i not in joints:
            # result = False
            errors.append(i)
    if errors:
        result_info = {'result': 'ERROR', 'info': errors}
    else:
        result_info = {'result': 'OK', 'info': []}

    return result_info


def checkLighting():
    """
    适用于所有阶段，返回都是正常的，只不过提醒
    """
    light_types = ['aiAreaLight','aiMeshLight','aiSkyDomeLight','aiPhotometricLight','aiLightPortal','aiSkyDomeLight','ambientLight',
                   'directionalLight','pointLight','spotLight','areaLight','volumeLight']

    light_list = []

    for i in light_types:
        light_shape_list = cmds.ls(type=i)
        if light_shape_list:
            light_list.extend(light_shape_list)
    result_info = {'result': 'TIP', 'info': light_list}

    return result_info

def checkYPos():
    """
    检测模型的顶点的Y轴坐标是否低于0
    """
    meshs = cmds.ls(type='mesh')
    down_y_zeros = []
    for m in meshs:
        #cmds.setAttr(m+'.displayColors',1)
        vertices = cmds.ls(m + '.vtx[*]', fl=1)
        for v in vertices:
            yPos = cmds.xform(v, q=True, worldSpace=True, t=True)
            if yPos[1] < 0 and m not in down_y_zeros:
                down_y_zeros.append(m)
                #vs = pm.ls(v)
                #vs[0].setColor((1,0,0))
    result_info = {'result': 'TIP', 'info': down_y_zeros}

    return result_info

def checkCGTW():
    p = os.popen('tasklist /FI "IMAGENAME eq CgTeamWork.exe"' )
    if p.read().count('CgTeamWork.exe') > 0:
        return True
    else:
        return False



def detectionByPipeline(pipeline,eps,asset_shot_name,task_name=None):
    """
    通过阶段名称来检测
    :param pipeline: 阶段名称
    :param eps: 集数名称  排期Asset
    :param asset_shot_name: 资产或镜头名称
    :param task_name: 任务名称  主要是绑定用来检测
    :return:
    """
    checks = {}
    optimizeScene_result = optimizeScene()
    checkLighting_result = checkLighting()

    checks['optimizeScene_result'] = optimizeScene_result
    checks['checkLighting_result'] = checkLighting_result
    if pipeline not in ['cfx']:
        checkName_result = checkName()
        checks['checkName_result'] = checkName_result

    if pipeline == 'ani':
        checkMainCamera_result = checkMainCamera(asset_shot_name) if eps != 'Asset' else {'result':'OK','info':''}
        checkDisplayLayers_result = checkDisplayLayers()
        checkRenderLayers_result = checkRenderLayers()
        checkPrimMaterial_result = checkPrimMaterial()
        checks['checkMainCamera_result'] = checkMainCamera_result
        checks['checkDisplayLayers_result'] = checkDisplayLayers_result
        checks['checkRenderLayers_result'] = checkRenderLayers_result
        checks['checkPrimMaterial_result'] = checkPrimMaterial_result


    elif pipeline == 'rig':
        # 仅当资产任务是绑定人的任务时才检测骨骼名称
        checkRigGrp_result = checkRigGrp()
        checkDisplayLayers_result = checkDisplayLayers()
        checkRenderLayers_result = checkRenderLayers()
        checkHumanRig_result = checkHumanRig() if task_name and task_name.endswith('human') else {'result':'OK','info':[]}
        checks['checkRigGrp_result'] = checkRigGrp_result
        checks['checkDisplayLayers_result'] = checkDisplayLayers_result
        checks['checkRenderLayers_result'] = checkRenderLayers_result
        checks['checkHumanRig_result'] = checkHumanRig_result


    elif pipeline == 'mm':
        checkMainCamera_result = checkMainCamera(asset_shot_name)
        # checkCameraBGImg_result = checkCameraBGImg(asset_shot_name)
        checkLockCamera_result = checkLockCamera(asset_shot_name)
        checkRenderLayers_result = checkRenderLayers()
        checks['checkMainCamera_result'] = checkMainCamera_result
        # checks['checkCameraBGImg_result'] = checkCameraBGImg_result
        checks['checkLockCamera_result'] = checkLockCamera_result
        checks['checkRenderLayers_result'] = checkRenderLayers_result

    elif pipeline == 'mod':
        checkDisplayLayers_result = checkDisplayLayers()
        checkRenderLayers_result = checkRenderLayers()
        # checkTex_result =checkMaterialTexture() # 模型不需要检测贴图是否在网盘上
        checkPrimMaterial_result = checkPrimMaterial()
        checkUV_result = checkUV()
        # checkColorSpace_result = checkColorSpace()
        checkOverFourFace_result = checkOverFourFace()
        checkCamera_result = checkCamera()
        checkYPos_result = checkYPos()

        checks['checkDisplayLayers_result'] = checkDisplayLayers_result
        checks['checkRenderLayers_result'] = checkRenderLayers_result
        # checks['checkTex_result'] = checkTex_result
        checks['checkPrimMaterial_result'] = checkPrimMaterial_result
        checks['checkUV_result'] = checkUV_result
        # checks['checkColorSpace_result'] = checkColorSpace_result
        checks['checkOverFourFace_result'] = checkOverFourFace_result
        checks['checkCamera_result'] = checkCamera_result
        checks['checkYPos_result'] = checkYPos_result

    elif pipeline == 'cfx':
        checkDisplayLayers_result = checkDisplayLayers()
        checkRenderLayers_result = checkRenderLayers()
        checkPrimMaterial_result = checkPrimMaterial()
        checkUV_result = checkUV()
        # checkColorSpace_result = checkColorSpace()
        checkOverFourFace_result = checkOverFourFace()
        checkCamera_result = checkCamera()
        # checkYPos_result = checkYPos()

        checks['checkDisplayLayers_result'] = checkDisplayLayers_result
        checks['checkRenderLayers_result'] = checkRenderLayers_result
        # checks['checkPrimMaterial_result'] = checkPrimMaterial_result
        checks['checkUV_result'] = checkUV_result
        # checks['checkColorSpace_result'] = checkColorSpace_result
        checks['checkOverFourFace_result'] = checkOverFourFace_result
        checks['checkCamera_result'] = checkCamera_result
        # checks['checkYPos_result'] = checkYPos_result

    elif pipeline == 'env':
        checkMainCamera_result = checkMainCamera(asset_shot_name)
        checkCameraBGImg_result = checkCameraBGImg(asset_shot_name)
        checkLockCamera_result = checkLockCamera(asset_shot_name)
        checkDisplayLayers_result = checkDisplayLayers()
        checkRenderLayers_result = checkRenderLayers()
        checkDSO_result = checkDSO()
        checkTex_result =checkMaterialTexture()
        checks['checkMainCamera_result'] = checkMainCamera_result
        checks['checkCameraBGImg_result'] = checkCameraBGImg_result
        checks['checkLockCamera_result'] = checkLockCamera_result
        checks['checkDisplayLayers_result'] = checkDisplayLayers_result
        checks['checkRenderLayers_result'] = checkRenderLayers_result
        checks['checDSO_result'] = checkDSO_result
        checks['checkTex_result'] = checkTex_result





    return checks






# def detectionByPipeline(pipeline,eps,asset_shot_name):
#     """
#     通过阶段名称来检测
#     :param pipeline: 阶段名称
#     :param eps: 集数名称  排期Asset
#     :param asset_shot_name: 资产或镜头名称
#     :return:
#     """
#     result = {'result':True,'info':[]}
#     r = True
#     c = True
#     if pipeline == 'ani':
#         r = rename_detect()
#         optimizeScene()
#         clearLayers()
#         c = checkCamera(asset_shot_name) if eps!='Asset' else True
#
#
#     elif pipeline == 'rig':
#         r = rename_detect()
#         optimizeScene()
#         clearLayers()
#
#
#
#     elif pipeline == 'mm':
#         r = rename_detect()
#         optimizeScene()
#         # clearLayers()
#         c = checkCamera(asset_shot_name)
#
#     if not r:
#         result['result'] = False
#         result['info'].append(u'重名')
#     if not c:
#         result['result'] = False
#         result['info'].append(u'没有主相机')
#
#     return result


